package com.hengyue.quartz.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.hengyue.common.constants.ScheduleConstants;
import com.hengyue.common.core.entity.BaseEntity;
import com.hengyue.common.core.entity.CoreBaseDataEntity;
import com.hengyue.common.utils.StringUtils;
import com.hengyue.quartz.util.CronUtils;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.annotations.GenericGenerator;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.Serial;
import java.util.Date;


@Setter
@Getter
@Entity
public class SysJob extends BaseEntity {

    @Serial
    private static final long serialVersionUID = 1L;

    @GeneratedValue(generator = "SnowIdGenerator")
    @GenericGenerator(type = com.hengyue.common.utils.SnowIdGenerator.class, name = "SnowIdGenerator")
    @Id
    private Long id;

    @NotBlank(message = "序号不能为空")
    @Size(min = 0, max = 64, message = "任务名称不能超过10个字符")
    private String code;

    @NotBlank(message = "任务名称不能为空")
    @Size(min = 0, max = 64, message = "任务名称不能超过64个字符")
    private String jobName;

    private String jobGroup;

    @NotBlank(message = "调用目标字符串不能为空")
    @Size(min = 0, max = 500, message = "调用目标字符串长度不能超过500个字符")
    private String invokeTarget;

    @NotBlank(message = "Cron执行表达式不能为空")
    @Size(min = 0, max = 255, message = "Cron执行表达式不能超过255个字符")
    private String cronExpression;

    private String misfirePolicy = ScheduleConstants.MISFIRE_DEFAULT;

    private String concurrent;

    private String status;

    private String remark;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public Date getNextValidTime() {
        if (StringUtils.isNotEmpty(cronExpression)) {
            return CronUtils.getNextExecution(cronExpression);
        }
        return null;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("jobId", getId())
            .append("jobName", getJobName())
            .append("jobGroup", getJobGroup())
            .append("cronExpression", getCronExpression())
            .append("nextValidTime", getNextValidTime())
            .append("misfirePolicy", getMisfirePolicy())
            .append("concurrent", getConcurrent())
            .append("status", getStatus())
            .append("createBy", getCreateBy())
            .append("createTime", getCreateTime())
            .append("updateBy", getUpdateBy())
            .append("updateTime", getUpdateTime())
            .toString();
    }
}



